package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.constant.RedisAdvertConst;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.content.Content;
import com.dongdongshop.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页广告
 * @Author Eayon
 * @Date 2020/3/3 14:21
 */
@Controller
@RequestMapping("content")
public class ContentController {

    private static final Logger log = LoggerFactory.getLogger(ContentController.class);

    //通过网关访问广告微服务
    private static final String CONTENT_URL = "http://localhost:8765/contentservice/content";

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取首页类型广告信息
     * @param categoryId
     * @return
     */
    @PostMapping(value = "getContentByCategoryId")
    @ResponseBody
    public DataResult getContentByCategoryId(Long categoryId){
        List<Content> contents = null;
        try {
            //判断如果redis中没有该类型广告数据
            if(!redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).hasKey(RedisAdvertConst.CATEGORY+categoryId)){
                //使用HTTP Client调用广告服务获取数据
                //设置请求参数
                Map<String,String> params = new HashMap<>();
                //该服务接收的是路径参数，但是还是要给一个空的MAP
                String dataResultStr = HttpClientUtil.doGet(CONTENT_URL + "/findByCategoryId/" + categoryId, params);
                DataResult<List<Content>> dataResult = JSONObject.parseObject(dataResultStr, DataResult.class);
                contents = dataResult.getData();
                redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).put(RedisAdvertConst.CATEGORY+categoryId,contents);
            }else{
                 contents = (List<Content>)redisTemplate.boundHashOps(RedisAdvertConst.INDEXADVER).get(RedisAdvertConst.CATEGORY + categoryId);
            }
        }catch (Exception e){
            log.error("初始化首页广告异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),contents);
    }
}
